package video.background.Utils;

import com.alibaba.druid.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * @program: video-backgroud
 * @description: 将前端输入的MultipartFile保存在本地
 * @author: hlt
 * @create: 2023-08-14 14:28
 **/
public class MultipartFileUtils {
    /**
     *
     * @param file
     * @param targetDirPath 存储MultipartFile文件的目标文件夹
     * @return 文件的存储的绝对路径
     */
    public static String saveMultipartFile(MultipartFile file, String targetDirPath,String name) throws IOException {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            return null;
        } else {
            /*获取文件原名称*/
            String originalFilename = file.getOriginalFilename();
            /*获取文件格式*/
            String fileFormat = originalFilename.substring(originalFilename.lastIndexOf("."));
            System.out.println(fileFormat);
            toFile = new File(targetDirPath + "/" + name + fileFormat);
            System.out.println("filePath: " + targetDirPath + "/" + name + fileFormat);
            String absolutePath = null;
            InputStream ins = null;
            try {
                absolutePath = toFile.getCanonicalPath();   // 返回标准的绝对路径
//                absolutePath = toFile.getAbsolutePath();
                System.out.println("absolutePath: " + absolutePath);
                /*判断路径中的文件夹是否存在，如果不存在，先创建文件夹*/
                String dirPath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
                System.out.println("dirPath: " + dirPath);
                File dir = new File(dirPath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                if (file.isEmpty()){
                    System.out.println("前端文件为空！");
                    return null;
                }
                ins = file.getInputStream();
                inputStreamToFile(ins, toFile);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    assert ins != null;
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("文件流关闭失败！");
                }
            }
            return absolutePath;
        }
    }

    public static String saveFile(MultipartFile file, String folderPath, String fileName) throws IOException {
        // 确保文件夹路径存在
        if (StringUtils.isEmpty(folderPath)) {
            throw new IllegalArgumentException("文件夹路径不能为空");
        }
        File file1 = new File(fileName + "/" + fileName + ".mp3");
        String absolutePath = file1.getCanonicalPath();
        String dirPath = absolutePath.substring(0, absolutePath.lastIndexOf(File.separator));
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 确保文件名不为空
        if (StringUtils.isEmpty(fileName)) {
            System.out.println("文件名不能为空");
        }

        // 生成新的文件名
        String newFileName = fileName + ".mp3";

        // 构建目标文件路径
        Path targetFilePath = new File(dir, newFileName).toPath();
        System.out.println("文件的保存路径：" + targetFilePath.toString());

        // 保存文件
        try {
            Files.copy(file.getInputStream(), targetFilePath, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("无法保存文件");
        }

        // 返回文件的绝对路径
        return targetFilePath.toAbsolutePath().toString();
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     *
     * @param file
     */
    public static void deleteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

    public static String deleteFile(String path) throws IOException {
        Path pa = Paths.get(path);
        Files.deleteIfExists(pa);
        return "删除成功！";
    }
}
